<template>
  <div>
    <Row style="align-items: flex-start;margin-bottom:5px;display:block">
      <Col :lg="10" :xs="22" offset="0.5">
        <vxe-toolbar :refresh="{ query: reload }" print v-if="isUpdate">
          <template #buttons>
            <vxe-button size="mini" status="primary" @click="impotEvent"
              >导入</vxe-button
            >
            <vxe-button size="mini" status="primary" @click="exportFile"
              >导出</vxe-button
            >
            <vxe-button size="mini" status="primary" @click="addRow"
              >新增</vxe-button
            >
            <vxe-button size="mini" status="danger" @click="delRow"
              >删除</vxe-button
            >
            <vxe-button size="mini" @click="saveData">保存</vxe-button>
          </template>
        </vxe-toolbar>
        <vxe-table
          ref="xTable"
          border
          highlight-hover-row
          show-overflow
          :edit-rules="validRules"
          class="sortable-row-demo"
          :data="tablePage.listPage"
          :print-config="{}"
          :export-config="{
            filename: filename(),
            columnFilterMethod: filterExport1,
            type: 'cvs'
          }"
          :loading="loading"
          :edit-config="{ trigger: 'click', mode: 'cell', enabled: isUpdate  }"
        >
          <vxe-column v-if="isUpdate" type="checkbox" width="60"></vxe-column>
          <vxe-column v-if="isUpdate" width="60">
            <template #default>
              <span class="drag-btn">
                <i class="vxe-icon--menu"></i>
              </span>
            </template>
            <template #header>
              <vxe-tooltip
                v-model="showHelpTip1"
                content="按住后可以上下拖动排序！"
                enterable
              >
                <i
                  class="vxe-icon--question"
                  @click="showHelpTip1 = !showHelpTip1"
                ></i>
              </vxe-tooltip>
            </template>
          </vxe-column>
          <vxe-column
            field="speed"
            title="转速(rpm)"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
          <vxe-column
            field="torque"
            title="扭矩(Nm)"
            :edit-render="{ name: 'input' }"
          ></vxe-column>
        </vxe-table>

        <vxe-pager
          :current-page="tablePage.currentPage"
          :page-size="tablePage.pageSize"
          :total="tablePage.totalResult"
          :layouts="[
            'PrevPage',
            'JumpNumber',
            'NextPage',
            'FullJump',
            'Sizes',
            'Total'
          ]"
          @page-change="handlePageChange"
        >
        </vxe-pager>
      </Col>
      <Col :lg="12" :xs="22" offset="0.5">
        <div style="height:400px;" id="b"></div>
      </Col>
    </Row>
  </div>
</template>

<script>
import { torqueConverterLambdaApi } from "@/api/torque-converter-lambda";
import Sortable from "sortablejs";
import { engineApi } from "@/api/engine";
import { engineExternalCharacteristicApi } from "@/api/engine-external-characteristic";
import { engineReverseApi } from "@/api/engine-reverse";
import { engineThousandApi } from "@/api/engine-thousand";
import XEUtils from "xe-utils";
import XLSX, { WorkSheet } from "xlsx";
const PAGE_SIZE_INIT = 20;
export default {
  name: "EngCmp1",
  components: {},
  props: {
    id: {
      type: Number
    },
    isUpdate: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      loading: false,
      validRules: {
        speed: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }],
        torque: [{ pattern: "^[0-9]+.?[0-9]*$", message: "请输入数字类型" }]
      },
      sortable1: null,
      showHelpTip1: false,
      detail: {}, // 详情信息
      torqueConvertId: null,
      tableData: [], // 表格列表数据-- 总数据
      tablePage: {
        currentPage: 1,
        pageSize: 10,
        totalResult: 0,
        listPage: []
      }
    };
  },
  computed: {},
  watch: {
    /// 深度监听，可监听到对象、数组的变化  (table数据变化时，渲染echart)
    tableData: {
      handler(newVal, oldVal) {
        this.renderEchart();
      },
      deep: true // true 深度监听
    }
  },
  filters: {},
  created() {
    // 启动列名拖动
    this.columnDrop2();
  },
  mounted() {
    // 初始化数据
    this.initData();

    this.rowDrop();
  },
  beforeCreate() {},
  beforeMount() {},
  beforeUpdate() {},
  updated() {},
  beforeDestroy() {},
  destroyed() {},
  activated() {},
  methods: {
    filename() {
      return (
        "倒拖特性曲线" +
        new Date(+new Date() + 8 * 3600 * 1000)
          .toJSON()
          .substr(0, 19)
          .replace("T", "")
          .replaceAll("-", "")
          .replaceAll(":", "")
      );
    },
    filterExport1(data) {
      // 返回false 就是导出不显示
      if (!data.column.title) return false;
      if (data.column.type == "checkbox") return false;
      return true;
    },
    // 刷新表格
    reload() {
      const $table = this.$refs.xTable;
      // 清除所有状态
      $table.clearAll();
      this.torqueConvertId = this.$route.query.id;
      // 初始化数据
      this.initData();
    },
    columnDrop2() {
      this.$nextTick(() => {
        const $table = this.$refs.xTable;
        this.sortable2 = Sortable.create(
          $table.$el.querySelector(
            ".body--wrapper>.vxe-table--header .vxe-header--row"
          ),
          {
            handle: ".vxe-header--column:not(.col--fixed)",
            onEnd: ({ item, newIndex, oldIndex }) => {
              const { fullColumn, tableColumn } = $table.getTableColumn();
              const targetThElem = item;
              const wrapperElem = targetThElem.parentNode;
              const newColumn = fullColumn[newIndex];
              if (newColumn.fixed) {
                // 错误的移动
                if (newIndex > oldIndex) {
                  wrapperElem.insertBefore(
                    targetThElem,
                    wrapperElem.children[oldIndex]
                  );
                } else {
                  wrapperElem.insertBefore(
                    wrapperElem.children[oldIndex],
                    targetThElem
                  );
                }
                return this.$XModal.message({
                  content: "固定列不允许拖动！",
                  status: "error"
                });
              }
              // 转换真实索引
              const oldColumnIndex = $table.getColumnIndex(
                tableColumn[oldIndex]
              );
              const newColumnIndex = $table.getColumnIndex(
                tableColumn[newIndex]
              );
              // 移动到目标列
              const currRow = fullColumn.splice(oldColumnIndex, 1)[0];
              fullColumn.splice(newColumnIndex, 0, currRow);
              $table.loadColumn(fullColumn);
            }
          }
        );
      });
    },
    getById() {
      torqueConverterLambdaApi.getById(this.torqueConvertId).then(res => {
        if (res.data) {
          this.detail = res.data;
        }
      });
    },

    // 行数据移动
    rowDrop() {
      this.$nextTick(() => {
        const xTable = this.$refs.xTable;
        this.sortable1 = Sortable.create(
          xTable.$el.querySelector(".body--wrapper>.vxe-table--body tbody"),
          {
            handle: ".drag-btn",
            onEnd: ({ newIndex, oldIndex }) => {
              const currRow = this.tableData.splice(oldIndex, 1)[0];
              this.tableData.splice(newIndex, 0, currRow);
            }
          }
        );
      });
    },
    // 翻页
    handlePageChange({ currentPage, pageSize }) {
      this.tablePage.currentPage = currentPage;
      this.tablePage.pageSize = pageSize;
      this.findList();
    },

    findList() {
      // 总数据
      this.tablePage.totalResult = this.tableData.length;
      this.tablePage.listPage = this.tableData.slice(
        (this.tablePage.currentPage - 1) * this.tablePage.pageSize,
        this.tablePage.currentPage * this.tablePage.pageSize
      );
    },
    exportFile() {
      this.$refs.xTable.exportData({ type: "csv" });
    },
    // 导入
    impotEvent() {
      this.$refs.xTable
        .readFile({
          types: ["xls", "xlsx", "csv"]
        })
        .then(params => {
          debugger;
          const { files } = params;
          const fileReader = new FileReader();
          fileReader.onload = ev => {
            const data = ev.target.result;
            const workbook = XLSX.read(data, { type: "binary" });
            const csvData = XLSX.utils.sheet_to_csv(workbook.Sheets.Sheet1);
            const tableData = [];
            // 解析数据csvData
            csvData.split("\n").forEach((vRow, index) => {
              if (index == 0) {
                return;
              }
              if (vRow) {
                const vCols = vRow.split(",");
                const item = {};
                vCols.forEach((val, cIndex) => {
                  if (cIndex == 0) {
                    item["speed"] = val;
                  } else if (cIndex == 1) {
                    item["torque"] = val;
                  }
                  item["index"] = Number(
                    Math.random()
                      .toString()
                      .substr(2, 10) + Date.now()
                  ).toString(36);
                });
                tableData.push(item);
              }
            });
            this.tableData = tableData;
            this.findList();
          };
          fileReader.readAsBinaryString(files[0]);
        });
    },
    /**
     * @desc 渲染echart
     * @sicne 2021/11/13
     */
    renderEchart() {
      // 生成 [x, y] 坐标
      let tempTable = [...this.tableData];
      tempTable.sort((a, b) => a.speed - b.speed);
      const data = [];
      tempTable.forEach(item => {
        const temp = [];
        temp.push(item.speed);
        temp.push(item.torque);
        data.push(temp);
      });
      const option = {
        title: {
          text: "倒拖特性曲线"
        },
        tooltip: {
          trigger: "item",
          formatter: function(item) {
            const x = item.data[0];
            const y = item.data[1];
            return `转速：${x}<br>扭矩：${y}`;
          }
        },
        /* legend: {
          x: 'right',
          data:['变矩比','能容系数','效率%'],
          textStyle:{
            fontsize:5
          }
        }, */
        grid: {
          left: "10%",

          bottom: "3%",
          containLabel: true
        },

        xAxis: {
          name: "转速(rpm)",
          nameLocation: "center",
          type: "value",
          axisLine: { onZero: false },
          splitLine: {
            show: false
          }
        },
        yAxis: [
          {
            name: "扭矩",
            axisLine: {
              lineStyle: {
                color: "#102b6a"
              },
              show: true
            },
            type: "value",
            position: "left",
            splitLine: {
              show: false
            }
          }
        ],

        series: [
          {
            id: "a",
            name: "扭矩(Nm)",
            type: "line",
            smooth: true,
            symbolSize: 5,
            data: data
          }
        ]
      };

      const myChart = this.echarts.init(document.getElementById("b"));
      myChart.clear();
      myChart.setOption(option);
    },

    /**
     * @desc 添加行数据
     */
    addRow() {
      const $table = this.$refs.xTable;
      const record = {
        speed: null,
        torque: null,
        index: new Date().getTime()
      };
      this.tableData.push(record);
      this.findList();
      const { row: newRow } = $table.insertAt(record, -1);
      $table.setActiveCell(newRow, "speed");
      this.reRenderTable();
    },
    reRenderTable() {
      const newData = this.tablePage.listPage;
      this.tablePage.listPage = [];
      setTimeout(() => {
        this.tablePage.listPage = newData;
      }, 100);
    },

    /**
     * @desc 删除行数据
     */
    async delRow() {
      const { rows } = await this.$refs.xTable.removeCheckboxRow();
      if (rows && rows.length > 0) {
        const newArr = [];
        const tempar = rows.map(item => item.index);
        this.tableData.forEach(item => {
          if (tempar.indexOf(item.index) == -1) {
            newArr.push(item);
          }
        });
        this.tableData = newArr;
      } else {
        this.$Message.warning("没有可删除的数据！");
      }
    },

    saveData() {
      // 数据验证
      if (!(this.tableData && this.tableData.length > 0)) {
        this.$Message.warning("没有可保存的数据！");
        return;
      }

      const speed = this.tableData.map(item => item.speed);
      const torque = this.tableData.map(item => item.torque);
      const throat = this.tableData.map(item => item.throat);
      const power = this.tableData.map(item => item.power);

      const param = {
        engineId: this.id,
        speed: JSON.stringify(speed),
        torque: JSON.stringify(torque),
        power: JSON.stringify(power),
        throat: JSON.stringify(throat),
        tableData: JSON.stringify(this.tableData)
      };
      this.loading = true;
      engineReverseApi
        .addEngineReverse(param)
        .then(res => {
          this.$Message.warning("保存成功");
        })
        .finally(() => {
          this.loading = false;
        });
    },

    /**
     * 初始化列表数据
     */
    initData() {
      this.loading = true;
      engineReverseApi
        .getByEngineId(this.id)
        .then(res => {
          const data = res.data;
          if (data) {
            // 组合table数据

            const tableData = JSON.parse(data.tableData);
            if (tableData && tableData.length > 0) {
              this.tableData = tableData;
              this.findList();
              this.renderEchart();
            }
          }
        })
        .finally(() => {
          this.loading = false;
        });
    }
  }
};
</script>
<style>
.sortable-row-demo .drag-btn {
  cursor: move;
  font-size: 12px;
}
.sortable-row-demo .vxe-body--row.sortable-ghost,
.sortable-row-demo .vxe-body--row.sortable-chosen {
  background-color: #dfecfb;
}
</style>
<style>
#cont {
  background-color: #fff;
  padding-top: 10px;
}

.tb-row1 {
  border: 1px solid #eee;
}

.tb-row1 > div {
  border-right: 1px solid #eee;
  height: 44px;
  line-height: 44px;
  font-size: 16px;
  padding-left: 10px;
}

.tb-row1 > div:first-child {
  color: #666;
  background: #f5f5f5;
  text-align: center;
  font-weight: bold;
}

.tb-row1 > div:nth-child(3) {
  color: #666;
  background: #f5f5f5;
  text-align: left;
  font-weight: bold;
  text-align: center;
}

.tb-row1 > div:last-child {
  border-right: 0;
}

.form-ex {
  margin-bottom: 20px;
}

.form-ex > div {
  width: 100px;
  display: inline;
}
</style>
